#!/usr/bin/env python

"""
build model executable
"""

import sys, os

_CIMEROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..","..","..","..")
sys.path.append(os.path.join(_CIMEROOT, "scripts", "Tools"))

from standard_script_setup import *
from CIME.buildlib         import parse_input
from CIME.case             import Case
from CIME.utils            import expect, run_cmd

logger = logging.getLogger(__name__)

###############################################################################
def _main_func():
###############################################################################

    caseroot, libroot, _ = parse_input(sys.argv)

    logger.info("Building a single executable version of target coupled model")

    with Case(caseroot) as case:
        casetools = case.get_value("CASETOOLS")
        cimeroot  = case.get_value("CIMEROOT")
        exeroot   = case.get_value("EXEROOT")
        gmake     = case.get_value("GMAKE")
        gmake_j   = case.get_value("GMAKE_J")
        model     = case.get_value("MODEL")
        num_esp   = case.get_value("NUM_COMP_INST_ESP")
        os.environ["PIO_VERSION"] = str(case.get_value("PIO_VERSION"))

    expect((num_esp is None) or (int(num_esp) == 1), "ESP component restricted to one instance")


    with open('Filepath', 'w') as out:
        out.write(os.path.join(caseroot, "SourceMods", "src.drv") + "\n")
        out.write(os.path.join(cimeroot, "src", "drivers", "moab", "main") + "\n")

    # build model executable

    makefile = os.path.join(casetools, "Makefile")
    exename = os.path.join(exeroot, model + ".exe")

    cmd = "%s exec_se -j %d EXEC_SE=%s MODEL=%s LIBROOT=%s -f %s "\
        % (gmake, gmake_j, exename, "driver", libroot, makefile)

    rc, out, _ = run_cmd(cmd, combine_output=True)
    expect(rc==0,"Command %s failed rc=%d\nout=%s"%(cmd,rc,out))
    logger.info(out)

###############################################################################

if __name__ == "__main__":
    _main_func()
